﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Common;
using System.Web.SessionState;
using System.Dynamic;
using Model;
using DAL;
using System.Data;
using System.Dynamic;
using System.Net;
using System.Text;
using System.Web.SessionState;
using JPushAPI;
using WxPayAPI;
using CsharpHttpHelper;
using System.Web.Caching;

namespace UI.tools
{
    /// <summary>
    /// API 的摘要说明
    /// </summary>
    public class API : IHttpHandler, IRequiresSessionState
    {
        static Dictionary<string, Func<string>> hs = new Dictionary<string, Func<string>>();
        static int counts = 1;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = JobRequest.GetRequestString("act");
            string result = string.Empty;
            //if (Commons.CheckSign())
            //{
                result = hs[action]();
            //}
            //else
            //{
            //    result = Commons.GetFaild("身份验证失败");
            //}
            context.Response.Write(result);
            context.Response.End();
        }
        static API()
        {
            /*登陆*/
            #region 修改密码
            hs.Add("Update_Pwd", () =>
            {
                //参数
                int userid = JobRequest.GetRequestInt("userid"); //用户ID
                string oldpwd = JobRequest.GetRequestString("oldpwd"); //旧密码
                string newpwd = JobRequest.GetRequestString("newpwd"); //新密码
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                UserInfo user = UserDAL.FindOneByID(userid);
                if (user.UserPwd != oldpwd)
                {
                    return Commons.GetFaild("旧密码错误");
                }
                bool ok = CommonDAL.UpdateColumnByID(user.ID, "userpwd", DESEncrypt.Encrypt(newpwd), "[user]");
                if (ok)
                {
                    return Commons.GetSuccess("修改成功", "");
                }
                else
                {
                    return Commons.GetFaild("修改失败");
                }
            });
            #endregion
            #region 获取活动
            hs.Add("Find_Active", () =>
            {
                //参数
                int userid = JobRequest.GetRequestInt("userid"); //用户ID
                int pageindex = JobRequest.GetRequestInt("pageindex"); //第几页
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int count = 0;
                PrizeRecordDAL.DecPrizeRecord();
                ActiveDAL.DecClickCount();
                List<ActiveInfo> list = ActiveDAL.FindPage("", userid, pageindex, 10, "", "", out count);
                foreach (ActiveInfo info in list)
                {
                    info.Ewm = info.Ewm + "?v=" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    info.Context = Commons.SubString(Commons.FilterHTML(info.Context), 100);
                }
                dynamic obj = new ExpandoObject();
                obj.list = list;
                obj.count = count;
                return Commons.GetSuccess("获取成功", obj);
            });
            #endregion
            #region 保存活动
            hs.Add("Save_Active", () =>
            {
                try
                {
                    //参数
                    int id = JobRequest.GetRequestInt("id"); //ID
                    int userid = JobRequest.GetRequestInt("userid"); //用户ID
                    string name = JobRequest.GetRequestString("name"); //活动名称
                    int moneytype = JobRequest.GetRequestInt("moneytype"); //红包类型
                    int count = JobRequest.GetRequestInt("count"); //红包数量
                    float onemoney = JobRequest.GetRequestFloat("onemoney") * 100; //单个红包金额
                    float allmoney = JobRequest.GetRequestFloat("allmoney") * 100; //红包总金额
                    string serverid = JobRequest.GetRequestString("serverid"); //服务id
                    string serverid2 = JobRequest.GetRequestString("serverid2"); //服务id
                    string serverid3 = JobRequest.GetRequestString("serverid3"); //服务id
                    string img = JobRequest.GetRequestString("img").Replace(Commons.domain, ""); //图片
                    string prizeimg = JobRequest.GetRequestString("prizeimg").Replace(Commons.domain, ""); //领奖图片
                    string weixin = JobRequest.GetRequestString("weixin").Replace(Commons.domain, "").Replace("/img/add-photo.png", ""); //二维码
                    string context = JobRequest.GetRequestString("context"); //公告内容
                    string link = JobRequest.GetRequestString("link"); //活动链接
                    string mobile = JobRequest.GetRequestString("mobile"); //联系电话
                    int prizetype = JobRequest.GetRequestInt("prizetype"); //领奖方式
                    int range = JobRequest.GetRequestInt("range"); //投放范围
                    string province = JobRequest.GetRequestString("province"); //省
                    string city = JobRequest.GetRequestString("city"); //市
                    string area = JobRequest.GetRequestString("area"); //区
                    string address = JobRequest.GetRequestString("address"); //详细地址
                    float lat = JobRequest.GetRequestFloat("lat"); //纬度
                    float lng = JobRequest.GetRequestFloat("lng"); //经度
                    int metre = JobRequest.GetRequestInt("metre"); //米
                    int degree = JobRequest.GetRequestInt("degree"); //匹配度
                    int activetype = JobRequest.GetRequestInt("activetype"); //活动类型
                    int needcount = JobRequest.GetRequestInt("needcount"); //所需数量
                    string skiplink = JobRequest.GetRequestString("skiplink"); //跳转链接
                    int giftcount = JobRequest.GetRequestInt("giftcount"); //礼品数量
                    int sex = JobRequest.GetRequestInt("sex"); //性别
                    int showover = JobRequest.GetRequestInt("showover"); //结束图提醒
                    int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                    //参数
                    if ((link.Contains("http://www.r1973.cn") || link.Contains("http://www.dchsksw.com")) && link.Contains("&code="))
                    {
                        link = link.Substring(0, link.IndexOf("&code="));
                    }
                    if (B.MyUser.ID != userid)
                    {
                        return Commons.GetFaild("身份有误");
                    }
                    UserInfo user = UserDAL.FindOneByID(userid);
                    
                    if (user.Role == 1)
                    {
                        //return Commons.GetFaild("您还不是会员");
                    }
                    if (prizetype <= 3)
                    {
                        if (allmoney <= 0)
                        {
                            return Commons.GetFaild("金额有误");
                        }
                        if (user.EndDate < DateTime.Now || user.State != 1)
                        {
                            if (count < 20000)
                            {
                                return Commons.GetFaild("非会员发送红包数量不能小于20000个");
                            }
                        }
                        if (id==0 && user.Money * 100 < allmoney)
                        {
                            return Commons.GetFaild("您的余额不足");
                        }
                    }
                    else
                    {
                        if (user.EndDate < DateTime.Now || user.State != 1)
                        {
                            return Commons.GetFaild("您还不是商家会员，暂时无法发布活动");
                        }
                    }
                    int ID = 0;
                    WeiXin wx = new WeiXin();
                    string path = "/upload/" + DateTime.Now.ToString("yyyy-MM-dd");
                    string root = HttpContext.Current.Server.MapPath(path);
                    if (!Directory.Exists(root))
                    {
                        Directory.CreateDirectory(root);
                    }
                    if (serverid != "")
                    {
                        string token = ConfigDAL.GetConfig().Token;
                        img = path + "/" + DateTime.Now.ToString("yyyyMMddHHmmssffff1") + ".jpg";
                        wx.SaveFile("https://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + token + "&media_id=" + serverid, img);
                    }
                    if (serverid2 != "")
                    {
                        string token = ConfigDAL.GetConfig().Token;
                        prizeimg = path + "/" + DateTime.Now.ToString("yyyyMMddHHmmssffff2") + ".jpg";
                        wx.SaveFile("https://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + token + "&media_id=" + serverid2, prizeimg);
                    }
                    if (serverid3 != "")
                    {
                        string token = ConfigDAL.GetConfig().Token;
                        weixin = path + "/" + DateTime.Now.ToString("yyyyMMddHHmmssffff3") + ".jpg";
                        wx.SaveFile("https://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + token + "&media_id=" + serverid3, weixin);
                    }
                    string linktext = "";
                    if (link.Contains("mp.weixin.qq.com"))
                    {
                        //WebBrowserCrawler wb = new WebBrowserCrawler();
                        //linktext = wb.GetReult(link);

                        HttpHelper http = new HttpHelper();
                        //获取到网页数据
                        HttpResult result = http.GetHtml(new HttpItem()
                        {
                            URL = link,
                            Referer = link,
                            Allowautoredirect = true
                        });
                        linktext = result.Html.Replace("data-src", "src");
                        linktext = Commons.NoScript(linktext).Replace("<span class=\"article-tag-card__title\">收录于话题</span>", "");
                        linktext = Commons.DownImg(linktext);
                        
                    }

                    ActiveInfo info = new ActiveInfo()
                    {
                        ID = id,
                        UserID = userid,
                        Name = name,
                        Img = img,
                        Link = link,
                        Mobile = mobile,
                        Context = context,
                        MoneyType = moneytype,
                        Count = count,
                        TakeCount = 0,
                        OneMoney = onemoney,
                        AllMoney = allmoney,
                        TakeMoney = 0,
                        PrizeType = prizetype,
                        Range = range,
                        Province = province,
                        City = city,
                        Area = area,
                        Metre = metre,
                        Lat = lat,
                        Lng = lng,
                        Address = address,
                        State = 1,
                        ClickCount = 0,
                        ShareCount = 0,
                        LinkText = linktext,
                        Degree = degree,
                        Flag = 1,
                        PrizeCount = 1,
                        ActiveType = activetype,
                        NeedCount = needcount,
                        PrizeImg = prizeimg,
                        SkipLink = skiplink,
                        GiftCount = giftcount,
                        WeiXin = weixin,
                        Sex = sex,
                        Keyword = user.Keyword,
                        ShowOver = showover,
                        CreateDate = DateTime.Now
                    };
                    if (id == 0)
                    {
                        ID = ActiveDAL.Save(info);
                        info.AllMoney = info.AllMoney / 100;
                        info.TakeMoney = info.TakeMoney / 100;
                        info.OneMoney = info.OneMoney / 100;
                        UserDAL.Charge(userid, -allmoney);
                        DataTable dt = GetTableSchema();
                        float avg = 0;
                        if (count > 0)
                        {
                            avg = allmoney / count;
                        }
                        for (int i = 0; i < count; i++)
                        {
                            float prizemoney = 0;
                            if (info.MoneyType == 1)
                            {
                                if (((int)avg) == 30)
                                {
                                    prizemoney = DataConvert.ToFloat("0.3");
                                }
                                else
                                {
                                    prizemoney = (info.AllMoney - info.TakeMoney) / (info.Count - info.TakeCount);
                                    float rand = 0;
                                    //if (prizemoney != 1)
                                    //{
                                        rand = DataConvert.ToFloat(new Random(Guid.NewGuid().GetHashCode()).Next((int)(-(prizemoney * 100 - 30)), (int)(prizemoney * 100 - 30 - 1))) / 100;
                                    //}
                                    prizemoney += rand;
                                    //把剩余的红包给最后一个人
                                    if (info.Count - info.TakeCount == 1)
                                    {
                                        prizemoney = info.AllMoney - info.TakeMoney;
                                    }
                                    if (count == 1)
                                    {
                                        prizemoney = info.AllMoney;
                                    }
                                    prizemoney = DataConvert.ToFloat(prizemoney.ToString("0.00"));
                                }
                                info.TakeMoney += prizemoney;
                                info.TakeCount++;
                            }
                            else
                            {
                                prizemoney = info.OneMoney;
                            }
                            DataRow dr = dt.NewRow();
                            dr[0] = 0;
                            dr[1] = 0;
                            dr[2] = ID;
                            dr[3] = prizemoney * 100;
                            dr[4] = 0;
                            dr[5] = DateTime.Parse("2017-01-01 00:00:00");
                            dt.Rows.Add(dr);
                        }
                        CommonDAL.BatchInsert(dt);

                        string ewm = path + "/" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
                        //wx.SaveFile("http://pan.baidu.com/share/qrcode?w=500&h=500&url=http://www.mengshen666.cn/activess.aspx?id=" + DESEncrypt.Encrypt(ID.ToString()), ewm);
                        //wx.SaveFile("http://bshare.optimix.asia/barCode?site=weixin&url=http://www.mengshen666.cn/activess.aspx?id=" + DESEncrypt.Encrypt(ID.ToString()), ewm);
                        //wx.SaveFile("http://qr.topscan.com/api.php?text=http://www.mengshen666.cn/activess.aspx?id=" + DESEncrypt.Encrypt(ID.ToString()), ewm);
                        wx.SaveFile("http://api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://www.mengshen666.cn/activesss.aspx?id=" + DESEncrypt.Encrypt(ID.ToString()), ewm);
                        CommonDAL.UpdateColumnByID(ID, "Ewm", ewm, "[active]");
                    }
                    else
                    {
                        ID = ActiveDAL.Update(info);

                    }
                    if (ID > 0)
                    {

                        return Commons.GetSuccess("保存成功", ID);
                    }
                    else
                    {
                        return Commons.GetFaild("保存失败");
                    }
                }
                catch (Exception ex)
                {
                    Commons.Log(ex.Message);
                    return "";
                }
            });
            #endregion
            #region 修改活动状态
            hs.Add("Active_State", () =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id");
                int state = JobRequest.GetRequestInt("state");
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                ActiveInfo info = ActiveDAL.FindOneByID(id);
                if (info.State == 4)
                {
                    return Commons.GetFaild("活动涉嫌违规，已被管理员暂停");
                }
                bool ok = CommonDAL.UpdateColumnByID(id, "State", state, "active");
                if (ok)
                {
                    if (state == 1)
                    {
                        //DeductionDAL.StartDeduction(id, 1);
                    }
                    if (state == 2)
                    {
                        //PrizeRecordDAL.DecPrizeRecord();
                        //DeductionDAL.PauseDeduction(id, 2);
                    }
                    /*
                    if (state == 2)
                    {
                        ActiveInfo active = ActiveDAL.FindOneByID(id);
                        UserDAL.Charge(active.UserID, (active.AllMoney - active.TakeMoney) * 100);
                    }
                    if (state == 1)
                    {
                        ActiveInfo active = ActiveDAL.FindOneByID(id);
                        UserDAL.Charge(active.UserID, -(active.AllMoney - active.TakeMoney) * 100);
                    }
                    */
                    return Commons.GetSuccess("操作成功", "");
                }
                else
                {
                    return Commons.GetFaild("操作失败");
                }
            });
            #endregion
            #region 删除活动
            hs.Add("Delete_Active", () =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id");
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                ActiveInfo active = ActiveDAL.FindOneByID(id);
                bool ok = CommonDAL.DeleteByID(id, "[active]");
                if (ok)
                {
                    //把活动剩余的钱退还到账户
                    UserDAL.Charge(active.UserID, active.AllMoney*100 - active.TakeMoney*100);
                    return Commons.GetSuccess("删除成功", "");
                }
                else
                {
                    return Commons.GetFaild("删除失败");
                }
            });
            #endregion

            #region 删除活动
            hs.Add("Find_Data", () =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id");
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                return Commons.GetSuccess("删除成功", "");
            });
            #endregion

            /*领红包*/
            #region 保存领红包记录
            hs.Add("Save_PrizeRecord", () =>
            {
                WeiXin wx = new WeiXin();
                string a=wx.PostInput(HttpContext.Current.Request);
                Commons.Log(a);
                if (Commons.GetWebClientIP() == "120.43.87.50")
                {
                    return Commons.GetFaild("非法操作");
                }
                try
                {
                    //参数
                    int sid = JobRequest.GetRequestInt("sid"); //SID
                    int userid = JobRequest.GetRequestInt("userid"); //userid
                    int createid = JobRequest.GetRequestInt("createid"); //活动创建人id
                    int money = DataConvert.ToInt(JobRequest.GetRequestFloat("money") * 100); //领奖金额
                    int prizetype = JobRequest.GetRequestInt("prizetype"); //红包类型
                    string flag = JobRequest.GetRequestString("flag"); //标记，客户端是否分享
                    string token = JobRequest.GetRequestString("token"); //token
                    string openid=JobRequest.GetRequestString("openid");
                    double lat = JobRequest.GetRequestDouble("lat");
                    double lng = JobRequest.GetRequestDouble("lng");
                    string province = JobRequest.GetRequestString("province");
                    string city = JobRequest.GetRequestString("city");
                    string area = JobRequest.GetRequestString("area");
                    string address = JobRequest.GetRequestString("address");
                    int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                    //参数

                    
                    ConfigInfo config = ConfigDAL.FindOneByID(1);

                    //Commons.Log(HttpContext.Current.Request.UserAgent + "aaaaaaaaaaaaaaaaaaaaaaaaaa");
                    //string host = HttpContext.Current.Request.UrlReferrer.Host;
                    //string agent = HttpContext.Current.Request.UserAgent.ToLower();
                    if (userid == 16832)
                    {
                        Commons.Log("*****************************我是郭俊杰");
                    }
                    if (userid == 16779)
                    {
                        Commons.Log("*****************************我是高波");
                    }
                    if (token=="" || DESEncrypt.Decrypt(token) != userid.ToString())
                    {
                        return Commons.GetFaild("身份验证不合法");
                    }
                    int ID = 0;
                    /*
                    if (flag == "share")
                    {
                        ActiveDAL.IncShareCount(sid);
                    }
                    */
                    //if (B.MyUser.ID != userid)
                    //{
                    //    return Commons.GetFaild("非法操作");
                    //}
                    //if (host != "www.mengshen666.cn" && host != "xyk.dnfn67.cn")
                    //{
                    //    return Commons.GetFaild("非法操作");
                    //}
                    //if (!agent.Contains("micromessenger"))
                    //{
                    //    return Commons.GetFaild("非法操作");
                    //}
                    if (PrizeRecordDAL.PrizeMoney(sid, userid) > 0)
                    {
                        return Commons.GetFaild("您已经领过啦");
                    }
                    if (PrizeRecordDAL.HasRedOver(sid))
                    {
                        return Commons.GetFaild("红包已领完");
                    }
                    if (PrizeRecordDAL.HasOutTime(sid, userid))
                    {
                        return Commons.GetFaild("超过30分钟没有领取红包，请刷新页面重新领取");
                    }

                    ActiveInfo active = ActiveDAL.FindOneByID(sid);
                    if (active.State == 2)
                    {
                        return Commons.GetFaild("活动已暂停");
                    }
                    if (active.Range == 2)
                    {
                        if (province.Trim() == "")
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                        if (!active.Province.Contains(province) && !province.Contains(active.Province))
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                    }
                    if (active.Range == 3)
                    {
                        if (city.Trim() == "")
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                        if (!active.City.Contains(city) && !city.Contains(active.City))
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                    }
                    if (active.Range == 4)
                    {
                        if (area.Trim() == "")
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                        if (!active.Area.Contains(area) && !area.Contains(active.Area))
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                    }
                    if (active.Range == 5)
                    {
                        if (Commons.CalcDistance(active.Lat,active.Lng,lat,lng)>active.Metre)
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                    }
                    if (userid == 16779)
                    {
                        //Commons.Log(lat + "-" + lng + "-" + lng + "-" + province + "-" + city + "-" + area + "-" + address);
                        //return Commons.GetFaild("哈哈，又是你");
                    }
                    if (money == 0)
                    {
                        return Commons.GetFaild("您来晚了，红包已经被领完啦");
                    }
                    if (active.AllMoney*100 - active.TakeMoney*100 - money < 0)
                    {
                        return Commons.GetFaild("您来晚了，红包已经被领完啦");
                    }
                    UserInfo user = UserDAL.FindOneByID(userid);
                    if (user.ID > 0)
                    {
                        double mymoney = PrizeRecordDAL.MyRedPacketMoney(sid, userid);
                        if (Math.Ceiling(mymoney) != money)
                        {
                            return Commons.GetFaild("领取失败");
                        }
                    }
                    if (money >= config.MaxMoney)
                    {
                        active.IsAuto = 0;
                    }
                    if (HttpContext.Current.Cache.Get(sid + "-" + userid) + "" != "1")
                    {
                        HttpContext.Current.Cache.Insert(sid + "-" + userid, 1, null, DateTime.UtcNow.AddSeconds(60), TimeSpan.Zero);
                    }
                    else
                    {
                        return Commons.GetFaild("您已经领过啦");
                    }
                    int incount = DataConvert.ToInt(HttpContext.Current.Cache.Get(sid.ToString()));
                    HttpContext.Current.Cache.Insert(sid.ToString(), ++incount, null, DateTime.UtcNow.AddSeconds(60), TimeSpan.Zero);
                    if (incount > config.MaxRedCount)
                    {
                        CommonDAL.UpdateColumnByID(sid, "IsAuto", 0, "[active]");
                        HttpContext.Current.Cache.Insert(sid.ToString(), 0, null, DateTime.UtcNow.AddSeconds(60), TimeSpan.Zero);
                    }
                    string result = ""; Commons.Log2("哈哈哈哈000000000000000000000000");
                    if (active.IsAuto == 1)
                    {
                        UserInfo uu = UserDAL.FindOneByID(active.UserID);
                        Commons.Log2("哈哈哈哈111111111111111111111111");
                        result = WxPayAPI.WxPayApi.CompanyPay(user.OpenID, (int)money, uu.Business);
                        Common.Commons.Log2(result);
                    }
                    if (result.Contains("支付失败"))
                    {
                        return Commons.GetFaild("非实名用户账号不可领红包");
                    }
                    else
                    {
                        PrizeRecordInfo info = new PrizeRecordInfo()
                        {
                            UserID = userid,
                            SID = sid,
                            Money = money,
                            PrizeType = prizetype,
                            Province = province,
                            City = city,
                            Area = area,
                            Lat = lat,
                            Lng = lng,
                            Address = address,
                            IsAuto=active.IsAuto,
                            CreateID = createid,
                            CreateDate = DateTime.Now
                        };

                        ID = PrizeRecordDAL.Save(info);

                        if (ID > 0)
                        {
                            ActiveDAL.UpdateTakeMoney(sid, money);
                            if (DataConvert.ToFloat(active.AllMoney * 100) <= DataConvert.ToFloat(active.TakeMoney * 100 + money))
                            {
                                CommonDAL.UpdateColumnByID(sid, "State", 3, "active");
                            }
                            return Commons.GetSuccess("保存成功", ID);
                        }
                        else
                        {
                            return Commons.GetFaild("保存失败");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Commons.Log(ex.Message+"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
                }
                return "";
            });
            #endregion
            #region 保存领红包记录
            hs.Add("Save_PrizeRecordOfOne", () =>
            {
                    
                    //参数
                    int ewmid = JobRequest.GetRequestInt("ewmid"); //二维码ID
                    int sid = JobRequest.GetRequestInt("sid"); //SID
                    int userid = JobRequest.GetRequestInt("userid"); //userid
                    int createid = JobRequest.GetRequestInt("createid"); //活动创建人id
                    int money = DataConvert.ToInt(JobRequest.GetRequestFloat("money") * 100); //领奖金额
                    int prizetype = JobRequest.GetRequestInt("prizetype"); //红包类型
                    string flag = JobRequest.GetRequestString("flag"); //标记，客户端是否分享
                    int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                    //参数
                    string host = HttpContext.Current.Request.UrlReferrer.Host;
                    string agent = HttpContext.Current.Request.UserAgent.ToLower();
                    int ID = 0;
                    if (flag == "share")
                    {
                        ActiveDAL.IncShareCount(sid);
                    }
                    
                    
                    double mymoney = PrizeRecordDAL.MyRedPacketMoney(sid, userid);
                    if (Math.Ceiling(mymoney) != money)
                    {
                        //return Commons.GetFaild("领取失败");
                    }
                    if (B.MyUser.ID != userid)
                    {
                        return Commons.GetFaild("非法操作");
                    }
                    if (host != "www.mengshen666.cn" && host != "xyk.dnfn67.cn")
                    {
                        return Commons.GetFaild("非法操作");
                    }
                    if (!agent.Contains("micromessenger"))
                    {
                        return Commons.GetFaild("非法操作");
                    }


                    EwmInfo ewm = EwmDAL.FindOneByID(ewmid);
                    ActiveInfo active = ActiveDAL.FindOneByID(sid);
                    if (active.State == 2)
                    {
                        return Commons.GetFaild("活动已暂停");
                    }
                    if (ewm.UserID == userid)
                    {
                        return Commons.GetFaild("您已经领过啦");
                    }
                    if (ewm.IsTake == 1)
                    {
                        return Commons.GetFaild("您来晚了，红包已被领走");
                    }
                    int prizecount = PrizeRecordDAL.PrizeCount(sid, userid);
                    int today = PrizeRecordDAL.PrizeCount(userid);
                    if (prizecount >= active.PrizeCount)
                    {
                        return Commons.GetFaild("每人最多只能领取" + active.PrizeCount + "个红包");
                    }
                    if (today >= 5)
                    {
                        return Commons.GetFaild("每人每天最多只能领取5个红包");
                    }
                    if (money==0)
                    {
                        return Commons.GetFaild("领取红包失败，请重试");
                    }
                    if (HttpContext.Current.Cache.Get(sid + "-" + userid) + "" != "1")
                    {
                        HttpContext.Current.Cache.Insert(sid + "-" + userid, 1, null, DateTime.UtcNow.AddSeconds(60), TimeSpan.Zero);
                    }
                    else
                    {
                        return Commons.GetFaild("您已经领过啦");
                    }
                    PrizeRecordInfo info = new PrizeRecordInfo()
                    {
                        UserID = userid,
                        SID = sid,
                        Money = money,
                        PrizeType = prizetype,
                        Province = "",
                        City = "",
                        Area = "",
                        Lat = 0,
                        Lng = 0,
                        Address = "",
                        CreateID = createid,
                        CreateDate = DateTime.Now
                    };

                    ID = PrizeRecordDAL.Save(info);

                    if (ID > 0)
                    {
                        ActiveDAL.UpdateTakeMoney(sid, money);
                        if (DataConvert.ToFloat(active.AllMoney * 100) <= DataConvert.ToFloat(active.TakeMoney * 100 + money))
                        {
                            CommonDAL.UpdateColumnByID(sid, "State", 3, "active");
                        }
                        UserInfo user = UserDAL.FindOneByID(userid);
                        EwmDAL.Update(userid, 1, ewmid);
                        UserInfo uu = UserDAL.FindOneByID(active.UserID);
                        WxPayAPI.WxPayApi.CompanyPay(user.OpenID, money, uu.Business);
                        return Commons.GetSuccess("保存成功", ID);
                    }
                    else
                    {
                        return Commons.GetFaild("保存失败");
                    }
                   
                

            });
            #endregion
            #region 分享次数+1
            hs.Add("Inc_ShareCount", () =>
            {
                //参数
                int sid = JobRequest.GetRequestInt("sid");
                int userid = JobRequest.GetRequestInt("userid"); //userid
                int createid = JobRequest.GetRequestInt("createid"); //活动创建人id
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                bool ok = ActiveDAL.IncShareCount(sid);
                if (ok)
                {
                    VisitRecordInfo visit = new VisitRecordInfo()
                    {
                        UserID = userid,
                        SID = sid,
                        Province = "",
                        City = "",
                        Area = "",
                        Lat = 0,
                        Lng = 0,
                        Address = "",
                        CreateID = createid,
                        FCount = 1,
                        Flag = 2,
                        CreateDate = DateTime.Now
                    };
                    VisitRecordDAL.Save(visit);
                    return Commons.GetSuccess("操作成功", "");
                }
                else
                {
                    return Commons.GetFaild("操作失败");
                }
            });
            #endregion
            #region 保存领红包记录
            hs.Add("Save_PrizeRecord2", () =>
            {

                try
                {
                    //参数
                    int sid = JobRequest.GetRequestInt("sid"); //SID
                    int userid = JobRequest.GetRequestInt("userid"); //userid
                    int createid = JobRequest.GetRequestInt("createid"); //活动创建人id
                    int money = DataConvert.ToInt(JobRequest.GetRequestDouble("money") * 100); //领奖金额
                    int prizetype = JobRequest.GetRequestInt("prizetype"); //红包类型
                    string flag = JobRequest.GetRequestString("flag"); //标记，客户端是否分享
                    string token = JobRequest.GetRequestString("token"); //token
                    string openid = JobRequest.GetRequestString("openid");
                    double lat = JobRequest.GetRequestDouble("lat");
                    double lng = JobRequest.GetRequestDouble("lng");
                    string province = JobRequest.GetRequestString("province");
                    string city = JobRequest.GetRequestString("city");
                    string area = JobRequest.GetRequestString("area");
                    string address = JobRequest.GetRequestString("address");
                    int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                    //参数
                    if (HttpContext.Current.Cache.Get(sid + "-" + userid) + "" != "1")
                    {
                        HttpContext.Current.Cache.Insert(sid + "-" + userid, 1, null, DateTime.UtcNow.AddSeconds(60), TimeSpan.Zero);
                    }
                    else
                    {
                        return Commons.GetFaild("您已经领过啦");
                    }
                    string host = HttpContext.Current.Request.UrlReferrer.Host;
                    string agent = HttpContext.Current.Request.UserAgent.ToLower();
                    if (userid == 16832)
                    {
                        Commons.Log("*****************************我是郭俊杰");
                    }
                    if (userid == 16779)
                    {
                        Commons.Log("*****************************我是高波");
                        Commons.Log("*****************************" + agent);
                    }
                    if (token == "" || DESEncrypt.Decrypt(token) != userid.ToString())
                    {
                        return Commons.GetFaild("身份验证不合法");
                    }
                    int ID = 0;
                    /*
                    if (flag == "share")
                    {
                        ActiveDAL.IncShareCount(sid);
                    }
                    */
                    if (B.MyUser.ID != userid)
                    {
                        return Commons.GetFaild("非法操作");
                    }
                    if (host != "www.mengshen666.cn" && host != "xyk.dnfn67.cn")
                    {
                        return Commons.GetFaild("非法操作");
                    }
                    if (!agent.Contains("micromessenger"))
                    {
                        return Commons.GetFaild("非法操作");
                    }
                    if (PrizeRecordDAL.PrizeMoney(sid, userid) > 0)
                    {
                        return Commons.GetFaild("您已经领过啦");
                    }
                    if (PrizeRecordDAL.HasOutTime(sid, userid))
                    {
                        return Commons.GetFaild("超过1分钟没有领取红包，请刷新页面重新领取");
                    }

                    ActiveInfo active = ActiveDAL.FindOneByID(sid);
                    if (active.State == 2)
                    {
                        return Commons.GetFaild("活动已暂停");
                    }
                    if (active.Range == 2)
                    {
                        if (province.Trim() == "")
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                        if (!active.Province.Contains(province) && !province.Contains(active.Province))
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                    }
                    if (active.Range == 3)
                    {
                        if (city.Trim() == "")
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                        if (!active.City.Contains(city) && !city.Contains(active.City))
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                    }
                    if (active.Range == 4)
                    {
                        if (area.Trim() == "")
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                        if (!active.Area.Contains(area) && !area.Contains(active.Area))
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                    }
                    if (active.Range == 5)
                    {
                        if (Commons.CalcDistance(active.Lat, active.Lng, lat, lng) > active.Metre)
                        {
                            return Commons.GetFaild("您不在活动范围之内");
                        }
                    }
                    if (userid == 16779)
                    {
                        //Commons.Log(lat + "-" + lng + "-" + lng + "-" + province + "-" + city + "-" + area + "-" + address);
                        //return Commons.GetFaild("哈哈，又是你");
                    }
                    if (money == 0)
                    {
                        return Commons.GetFaild("您来晚了，红包已经被领完啦");
                    }
                    if (active.AllMoney * 100 - active.TakeMoney * 100 - money < 0)
                    {
                        return Commons.GetFaild("您来晚了，红包已经被领完啦");
                    }
                    UserInfo user = UserDAL.FindOneByID(userid);
                    if (user.ID > 0)
                    {
                        double mymoney = PrizeRecordDAL.MyRedPacketMoney(sid, userid);
                        if (mymoney != money)
                        {
                            Commons.Log(mymoney + "-------" + money);
                            return Commons.GetFaild("领取失败");
                        }
                    }
                    ConfigInfo config = ConfigDAL.FindOneByID(1);
                    if (money >= config.MaxMoney)
                    {
                        active.IsAuto = 0;
                    }
                    string result = "";
                    if (active.IsAuto == 1)
                    {
                        UserInfo uu = UserDAL.FindOneByID(active.UserID);
                        result = WxPayAPI.WxPayApi.CompanyPay(user.OpenID, (int)money, uu.Business);
                    }
                    if (result.Contains("余额不足"))
                    {
                        return Commons.GetFaild("余额不足不可领红包");
                    }
                    else if (result.Contains("支付失败"))
                    {
                        return Commons.GetFaild("非实名用户账号不可领红包");
                    }
                    else
                    {
                        PrizeRecordInfo info = new PrizeRecordInfo()
                        {
                            UserID = userid,
                            SID = sid,
                            Money = money,
                            PrizeType = prizetype,
                            Province = province,
                            City = city,
                            Area = area,
                            Lat = lat,
                            Lng = lng,
                            Address = address,
                            IsAuto = active.IsAuto,
                            CreateID = createid,
                            CreateDate = DateTime.Now
                        };

                        ID = PrizeRecordDAL.Save(info);

                        if (ID > 0)
                        {
                            ActiveDAL.UpdateTakeMoney(sid, money);
                            if (active.AllMoney * 100 <= active.TakeMoney * 100 + money)
                            {
                                CommonDAL.UpdateColumnByID(sid, "State", 3, "active");
                            }


                            return Commons.GetSuccess("保存成功", ID);
                        }
                        else
                        {
                            return Commons.GetFaild("保存失败");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Commons.Log(ex.Message + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
                }
                return "";
            });
            #endregion

            /*点赞*/
            #region 保存点赞记录
            hs.Add("Save_PraiseRecord", () =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //唯一ID
                int sid = JobRequest.GetRequestInt("sid"); //活动ID
                int shareuserid = JobRequest.GetRequestInt("shareuserid"); //用户ID
                int praiseuserid = JobRequest.GetRequestInt("praiseuserid"); //用户ID
                int type = JobRequest.GetRequestInt("type"); //类型
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int ID = 0;

                PraiseRecordInfo info = new PraiseRecordInfo()
                {
                    ID = id,
                    SID = sid,
                    ShareUserID = shareuserid,
                    PraiseUserID = praiseuserid,
                    Type= type,
                    CreateDate = DateTime.Now
                };
                if (type == 1)
                {
                    ActiveDAL.IncPraiseCount(sid);
                }
                if (id == 0)
                {
                    if (PraiseRecordDAL.IsPraise(sid, shareuserid, praiseuserid, type))
                    {
                        ID = 0;
                    }
                    else
                    {
                        ID = PraiseRecordDAL.Save(info);
                    }
                    ActiveInfo active=ActiveDAL.FindOneByID(sid);
                    int praisecount=PraiseRecordDAL.FindCountBySID(sid,shareuserid);
                    if (praisecount >= active.NeedCount)
                    {
                        ActiveDAL.UpdateTakeGiftCount(sid);
                        if (!FinishTaskDAL.IsExist(sid, shareuserid))
                        {
                            int num = FinishTaskDAL.MaxNum(sid);
                            if (num == 0)
                            {
                                num = 10001;
                            }
                            else
                            {
                                num = num + 1;
                            }
                            FinishTaskInfo finish = new FinishTaskInfo()
                            {
                                SID=sid,
                                UserID=shareuserid,
                                IsTake=0,
                                Num = num,
                                CreateDate=DateTime.Now
                            };
                            FinishTaskDAL.Save(finish);
                        }
                        if (active.GiftCount - active.TakeGiftCount == 1)
                        {
                            CommonDAL.UpdateColumnByID(sid, "State", 3, "active");
                        }
                    }
                    
                }
                if (ID > 0)
                {
                    return Commons.GetSuccess("保存成功", ID);
                }
                else
                {
                    return Commons.GetFaild((type==1?"点赞":"分享")+"成功");
                }
            });
            #endregion
            #region 获取完成活动的人
            hs.Add("Find_FinsihActive", () =>
            {
                //参数
                int sid = JobRequest.GetRequestInt("sid"); //活动ID
                int pageindex = JobRequest.GetRequestInt("pageindex"); //第几页
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int count = 0;
                List<dynamic> list = FinishTaskDAL.FinishTask(sid);
                dynamic obj = new ExpandoObject();
                obj.list = list;
                obj.count = count;
                return Commons.GetSuccess("获取成功", obj);
            });
            #endregion
            #region 修改是否已经领取奖品
            hs.Add("Set_IsTake", () =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id");
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                FinishTaskInfo info = FinishTaskDAL.FindOneByID(id);
                bool ok = false;
                if (info.IsTake == 0)
                {
                    ok = CommonDAL.UpdateColumnByID(id, "IsTake", 1, "finishtask");
                }
                else
                {
                    ok = CommonDAL.UpdateColumnByID(id, "IsTake", 0, "finishtask");
                }
                
                if (ok)
                {
                    return Commons.GetSuccess(info.IsTake==0 ? "礼品领取" : "取消" + "成功", "");
                }
                else
                {
                    return Commons.GetFaild("操作失败");
                }
            });
            #endregion

            /*客服*/
            #region 获取客服
            hs.Add("Find_Kf", () =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int id = new Random(DateTime.Now.Millisecond).Next(1, 100000);
                string user = UserDAL.FindOneByID(id).NickName;
                counts++;
                int count = 0;
                List<KfInfo> list = KfDAL.FindAll();
                dynamic obj = new ExpandoObject();
                obj.list = list;
                obj.count = count;
                return Commons.GetSuccess("获取成功", obj);
            });
            #endregion
            #region 获取微数据
            hs.Add("Find_WeiData", () =>
            {
                //参数
                int userid = JobRequest.GetRequestInt("userid"); //用户ID
                string begindate = JobRequest.GetRequestString("begindate"); //开始时间
                string enddate = JobRequest.GetRequestString("enddate"); //结束时间
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                dynamic obj = new ExpandoObject();
                List<dynamic> prizelist=PrizeRecordDAL.FindData(userid,begindate,enddate);
                List<dynamic> visitlist = VisitRecordDAL.FindData(userid, begindate, enddate);
                List<dynamic> sharelist = VisitRecordDAL.FindData2(userid, begindate, enddate);
                List<dynamic> list = new List<dynamic>();
                int day=30;
                DateTime datetime=DateTime.Now;
                if(begindate!="" && enddate!=""){
                    day= Commons.DateDiff(DataConvert.ToDateTime(begindate), DataConvert.ToDateTime(enddate),"D");
                    datetime=DataConvert.ToDateTime(enddate);
                }
                for(int i=0;i<day;i++)
                {
                    datetime=datetime.AddDays(i==0?0:-1);
                    dynamic prize = prizelist.FirstOrDefault(x => x.CreateDate.ToString("yyyy-MM-dd") == datetime.ToString("yyyy-MM-dd"));
                    if (prize == null) { prize = new ExpandoObject(); prize.PrizeCount = 0; prize.Money = 0; prize.CreateDate = datetime.ToString("yyyy-MM-dd"); }
                    dynamic visit = visitlist.FirstOrDefault(x => x.CreateDate.ToString("yyyy-MM-dd") == datetime.ToString("yyyy-MM-dd"));
                    if (visit == null) { visit = new ExpandoObject(); visit.OpenCount = 0;  visit.CreateDate = datetime.ToString("yyyy-MM-dd"); }
                    dynamic share = sharelist.FirstOrDefault(x => x.CreateDate.ToString("yyyy-MM-dd") == datetime.ToString("yyyy-MM-dd"));
                    if (share == null) { share = new ExpandoObject();  share.ShareCount = 0; share.CreateDate = datetime.ToString("yyyy-MM-dd"); }
                    if(i==0){
                        obj.TodayDate = datetime.ToString("MM月dd日");
                        obj.TodayOpenCount = visit.OpenCount;
                        obj.TodayShareCount = share.ShareCount;
                        obj.TodayPrizeCount = prize.PrizeCount;
                        obj.TodayMoney = prize.Money;
                    }else{
                        dynamic info = new ExpandoObject();
                        if (i == 1)
                        {
                            info.Date = "昨天";
                        }
                        else if (i == 2)
                        {
                            info.Date = "前天";
                        }
                        else
                        {
                            info.Date = datetime.ToString("MM月dd日");
                        }
                        info.OpenCount = visit.OpenCount;
                        info.ShareCount = share.ShareCount;
                        info.PrizeCount = prize.PrizeCount;
                        info.Money = prize.Money;
                        list.Add(info);
                    }
                }
                obj.list = list;
                return Commons.GetSuccess("获取成功", obj);
            });
            #endregion
            #region 转换经纬度
            hs.Add("Tran_Position", () =>
            {
                //参数
                string lat = JobRequest.GetRequestString("lat");
                string lng = JobRequest.GetRequestString("lng");
                int userid = JobRequest.GetRequestInt("userid");
                //参数
                WeiXin wx = new WeiXin();
                string position = wx.HttpGet("http://apis.map.qq.com/ws/coord/v1/translate?locations=" + lat + "," + lng + "&type=1&key=2STBZ-Q6VA4-FSAU4-DO7ZG-YN7T5-ZZFSF", "");
                return position;

            });
            #endregion
            #region 经纬度转化为地址
            hs.Add("Position_Address", () =>
            {
                //参数
                double lat = JobRequest.GetRequestDouble("lat");
                double lng = JobRequest.GetRequestDouble("lng");
                //参数
                WeiXin wx = new WeiXin();
                string position = wx.HttpGet("http://apis.map.qq.com/ws/geocoder/v1/?location="+lat+","+lng+"&key=2STBZ-Q6VA4-FSAU4-DO7ZG-YN7T5-ZZFSF&get_poi=0", "");
                return position;
            });
            #endregion

            /*合作申请*/
            #region 保存合作申请
            hs.Add("Save_Apply", () =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //唯一ID
                string name = JobRequest.GetRequestString("name"); //联系人
                string mobile = JobRequest.GetRequestString("mobile"); //手机号
                string city = JobRequest.GetRequestString("city"); //所在城市
                string comname = JobRequest.GetRequestString("comname"); //公司名称
                int adminid = JobRequest.GetRequestInt("adminid");//代理商id
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int ID = 0;
                ID= DataConvert.ToInt(CommonDAL.FindColumnByColumn("ID", "mobile", mobile, "[apply]"));
                if (ID > 0)
                {
                    return Commons.GetFaild("申请失败，该手机号已经申请过");
                }

                string headimg = "";
                int userid = 0;
                string nickname = "";
                if (B.MyUser != null)
                {
                    headimg=B.MyUser.HeadImg;
                    userid = B.MyUser.ID;
                    nickname = B.MyUser.NickName;
                }
                ApplyInfo info = new ApplyInfo()
                {
                    ID = id,
                    UserID = userid,
                    NickName = nickname,
                    HeadImg = headimg,
                    Name = name,
                    Mobile = mobile,
                    City = city,
                    ComName = comname,
                    Adminid = adminid,
                    CreateDate = DateTime.Now
                };
                
                if (id == 0)
                {
                    ID = ApplyDAL.Save(info);   
                }
                else
                {
                    ID = ApplyDAL.Update(info);
                }
                if (ID > 0)
                {
                    return Commons.GetSuccess("保存成功", ID);
                }
                else
                {
                    return Commons.GetFaild("保存成功");
                }
            });
            #endregion

            #region 获取微信支付参数
            hs.Add("GetWxPara", () =>
            {
                //参数
                int userid = JobRequest.GetRequestInt("userid"); //用户ID
                string openid = JobRequest.GetRequestString("openid");
                string flag = JobRequest.GetRequestString("flag"); //charge:充值   member:成为会员
                int allmoney = JobRequest.GetRequestInt("allmoney"); //充值金额（单位：分）
                int yingfu = JobRequest.GetRequestInt("yingfu"); //充值金额（单位：分）
                //参数
                dynamic dy = new ExpandoObject();
                try
                {

                    WxPayData data = new WxPayData();
                    string nonce_str = WxPayApi.GenerateNonceStr();
                    string timestamp = WxPayApi.GenerateTimeStamp();
                    data.SetValue("body", "亿销客");
                    data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
                    data.SetValue("total_fee", allmoney.ToString());
                    data.SetValue("openid", openid);
                    data.SetValue("trade_type", "JSAPI");
                    data.SetValue("attach", userid+"_" + flag+"_"+yingfu);
                    data.SetValue("nonce_str", nonce_str);//随机字符串
                    WxPayData result = WxPayApi.UnifiedOrder(data);
                    dy.prepay_id = result.GetValue("prepay_id");
                    
                    dy.appid = WxPayConfig.APPID;
                    WxPayData wp = new WxPayData();
                    wp.SetValue("appId", WxPayConfig.APPID);//公众账号ID
                    wp.SetValue("nonceStr", nonce_str);//随机字符串
                    wp.SetValue("timeStamp", timestamp);
                    wp.SetValue("signType", "MD5");
                    wp.SetValue("package", "prepay_id=" + dy.prepay_id);
                    dy.sign = wp.MakeSign();
                    dy.timestamp = timestamp;
                    dy.noncestr = nonce_str;
                }
                catch (Exception ex)
                {
                    Commons.Log(ex.Message);
                }
                return Commons.GetSuccess("保存成功", dy);
            });
            #endregion
            #region 获取H5微信支付参数
            hs.Add("GetH5WxPara", () =>
            {
                //参数
                int userid = JobRequest.GetRequestInt("userid"); //用户ID
                string flag = JobRequest.GetRequestString("flag"); // charge:充值   member:成为会员
                float allmoney = JobRequest.GetRequestFloat("allmoney"); //充值金额
                //参数
                string ip = Commons.GetWebClientIP();
                dynamic dy = new ExpandoObject();
                WxPayData data = new WxPayData();
                string nonce_str = WxPayApi.GenerateNonceStr();
                string timestamp = WxPayApi.GenerateTimeStamp();
                data.SetValue("body", "亿销客");
                data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
                data.SetValue("total_fee", DataConvert.ToInt(allmoney * 100));
                data.SetValue("trade_type", "MWEB");
                data.SetValue("attach", userid + "_" + flag);
                data.SetValue("nonce_str", nonce_str);//随机字符串
                data.SetValue("spbill_create_ip", ip);

                WxPayData result = WxPayApi.UnifiedOrder(data);
                dy.prepay_id = result.GetValue("prepay_id");
                dy.appid = WxPayConfig.APPID;
                dy.mchid = WxPayConfig.MCHID;
                dy.key = WxPayConfig.KEY;
                dy.appsecret = WxPayConfig.APPSECRET;
                WxPayData wp = new WxPayData();
                wp.SetValue("appid", WxPayConfig.APPID);//公众账号ID
                wp.SetValue("partnerid", WxPayConfig.MCHID);//商户号
                wp.SetValue("prepayid", dy.prepay_id);
                wp.SetValue("noncestr", nonce_str);//随机字符串
                wp.SetValue("timestamp", timestamp);
                wp.SetValue("package", timestamp);
                dy.sign = wp.MakeSign();
                dy.package = timestamp;
                dy.timestamp = timestamp;
                dy.noncestr = nonce_str;
                return Commons.GetSuccess("保存成功", dy);
            });
            #endregion

            #region 版本更新
            hs.Add("UpdateClient", () =>
            {
                dynamic dy = new ExpandoObject();
                //版本号
                dy.version = Commons.GetConfig("Version");
                //下载地址
                dy.url = Commons.domain + "/app/xinlian.apk";
                //app名字qiyebao
                dy.appname = "信联";
                string content = Commons.GetConfig("Content").Replace("\\n", "\n");
                //app更新内容
                dy.content = content == null ? "" : content;
                dy.appsize = Commons.GetConfig("AppSize");
                return SerializeHelper.ToJsonByDynamic(dy);
            });
            #endregion

            #region 获取香港服务器所需参数
            hs.Add("Find_HongKong", () =>
            {
                //参数
                int userid = JobRequest.GetRequestInt("userid"); //
                int activeid = JobRequest.GetRequestInt("activeid"); //
                //参数
                UserInfo uinfo = UserDAL.FindOneByID(userid);
                ActiveInfo active = ActiveDAL.FindOneByID(activeid);
                UserInfo pinfo = UserDAL.FindOneByID(active.UserID);
                double prizemoney = PrizeRecordDAL.PrizeMoney(active.ID, uinfo.ID);

                WeiXin wx = new WeiXin();
                string str = SerializeHelper.ToJson<UserInfo>(uinfo) + "△" + SerializeHelper.ToJson<ActiveInfo>(active) + "△" + SerializeHelper.ToJson<UserInfo>(pinfo) + "△" + prizemoney;
                return Commons.GetSuccess("获取成功", str);
            });
            #endregion
        }

        static bool CheckSign()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                string action = JobRequest.GetRequestString("act");
                string sign = JobRequest.GetRequestString("sign");
                sb.AppendFormat("account={0}&act={1}&key={2}", "Common_CLIENT", action, "365E6B86CE4E43A552G563078D5ADEFD");
                string signstr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "MD5").ToLower();
                return sign == signstr;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        //PC用
        public static void UploadAnnex(int sid, int userid, string flag, string imgs)
        {
            string[] imges = imgs.Split(',');
            if (imgs.Trim() != "")
            {
                foreach (string img in imges)
                {
                    string[] images = img.Split('*');
                    FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(images[0]));
                    AnnexInfo info = new AnnexInfo()
                    {
                        SID = sid,
                        UserID = userid,
                        Name = images[1],
                        Path = images[0],
                        Size = (int)file.Length,
                        Flag = flag,
                        Type = 1,
                        CreateDate = DateTime.Now
                    };
                    AnnexDAL.Save(info);
                }
            }
        }
        public static void UploadFile(int sid, int userid, string flag, string imgs)
        {
            string[] imges = imgs.Split(',');
            if (imgs.Trim() != "")
            {
                foreach (string img in imges)
                {
                    string[] images = img.Split('*');
                    FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(images[0]));
                    AnnexInfo info = new AnnexInfo()
                    {
                        SID = sid,
                        UserID = userid,
                        Name = images[1],
                        Path = images[0],
                        Size = (int)file.Length,
                        Flag = flag,
                        Type = 2,
                        CreateDate = DateTime.Now
                    };
                    AnnexDAL.Save(info);
                }
            }
        }
        //手机用
        public static void UploadAnnex(int sid,int userid, string flag)
        {
            var content = HttpContext.Current;
            string opath = "/upload/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            var rootpath = content.Server.MapPath(opath);
            if (!System.IO.Directory.Exists(rootpath))
            {
                Directory.CreateDirectory(rootpath);
            }
            string[] keys = content.Request.Files.AllKeys;
            for (int j = 0; j < content.Request.Files.Count; j++)
            {
                HttpPostedFile uploadFile = content.Request.Files[j];
                if (uploadFile.ContentLength > 0 && keys[j]=="img")
                {
                    string ext = Path.GetExtension(uploadFile.FileName);
                    string unique = DateTime.Now.ToString("HHmmssfff");
                    string file = rootpath + unique + ext;
                    string name = file.Substring(0, file.LastIndexOf('.'));
                    uploadFile.SaveAs(file);
                    string imgpath50 = name + "_50" + ext;
                    string imgpath100 = name + "_100" + ext;
                    string imgpath200 = name + "_200" + ext;
                    string imgpath500 = name + "_500" + ext;
                    string imgpath1000 = name + "_1000" + ext;
                    Thumbnail.MakeThumbnailImage(file, imgpath50, 50, 50);
                    Thumbnail.MakeThumbnailImage(file, imgpath100, 100, 100);
                    Thumbnail.MakeThumbnail(file, imgpath200, 200, 200);
                    Thumbnail.MakeThumbnailImage(file, imgpath500, 500, 500);
                    Thumbnail.MakeThumbnailImage(file, imgpath1000, 1000, 1000);

                    AnnexInfo info = new AnnexInfo()
                    {
                        SID=sid,
                        UserID=userid,
                        Name=uploadFile.FileName,
                        Path = opath + unique + ext,
                        Size=uploadFile.ContentLength,
                        Flag=flag,
                        Type=1,
                        CreateDate=DateTime.Now
                    };
                    AnnexDAL.Save(info);
                }

                if (uploadFile.ContentLength > 0 && keys[j] == "file")
                {
                    string ext = Path.GetExtension(uploadFile.FileName);
                    string unique = DateTime.Now.ToString("HHmmssfff");
                    string file = rootpath + unique + ext;
                    if (ext == "") { continue; }
                    string name = file.Substring(0, file.LastIndexOf('.'));
                    uploadFile.SaveAs(file);
                    AnnexInfo info = new AnnexInfo()
                    {
                        SID = sid,
                        UserID = userid,
                        Name = uploadFile.FileName,
                        Path = opath + unique + ext,
                        Size = uploadFile.ContentLength,
                        Flag = flag,
                        Type=2,
                        CreateDate = DateTime.Now
                    };
                    AnnexDAL.Save(info);

                }

            }
        }
        public static string UploadImg()
        {
            var content = HttpContext.Current;
            string opath = "/upload/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            var rootpath = content.Server.MapPath(opath);
            if (!System.IO.Directory.Exists(rootpath))
            {
                Directory.CreateDirectory(rootpath);
            }
            string str = "";
            for (int j = 0; j < content.Request.Files.Count; j++)
            {
                HttpPostedFile uploadFile = content.Request.Files[j];
                if (uploadFile.ContentLength > 0)
                {
                    string ext = Path.GetExtension(uploadFile.FileName);
                    string unique = DateTime.Now.ToString("HHmmssfff");
                    string file = rootpath + unique + ext;
                    string name = file.Substring(0, file.LastIndexOf('.'));
                    uploadFile.SaveAs(file);
                    string imgpath50 = name + "_50" + ext;
                    string imgpath100 = name + "_100" + ext;
                    string imgpath200 = name + "_200" + ext;
                    string imgpath500 = name + "_500" + ext;
                    string imgpath1000 = name + "_1000" + ext;
                    Thumbnail.MakeThumbnailImage(file, imgpath50, 50, 50);
                    Thumbnail.MakeThumbnailImage(file, imgpath100, 100, 100);
                    Thumbnail.MakeThumbnail(file, imgpath200, 200, 200);
                    Thumbnail.MakeThumbnailImage(file, imgpath500, 500, 500);
                    Thumbnail.MakeThumbnailImage(file, imgpath1000, 1000, 1000);
                    str = opath + unique + ext;
                }

            }
            return str;
        }
        public static DataTable GetTableSchema()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[] {
            new DataColumn("ID",typeof(int)),  
            new DataColumn("UserID",typeof(int)),  
            new DataColumn("ActiveID",typeof(int)),  
            new DataColumn("Money",typeof(double)),
            new DataColumn("IsTake",typeof(int)),
            new DataColumn("CreateDate",typeof(DateTime)),
            });
            return dt;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}